﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

namespace PreContractWeb.Administration
{
    public partial class UserManagement : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            bool isRoleAdmin = this.CheckUserPermission()[1];

            if (!isRoleAdmin)
            {
                this.divError.InnerHtml = AlertMessage.NoRoleAdminPermission;

                ScriptManager.RegisterClientScriptBlock(this.UpdatePanel1, this.GetType(), "", "<script>if(document.getElementById('ctl00_ContentPlaceHolder1_divConnect')!=null) document.getElementById('ctl00_ContentPlaceHolder1_divConnect').style.visibility='hidden';</script>", false);
                ScriptManager.RegisterClientScriptBlock(this.UpdatePanel1, this.GetType(), "", "<script>if(document.getElementById('ctl00_ContentPlaceHolder1_divError')!=null) document.getElementById('ctl00_ContentPlaceHolder1_divError').style.visibility='visible';</script>", false);


                //this.divConnect.Visible = false;
                //this.divError.Visible = true;

                this.divConnect.Style.Add("visibility", "hidden");
                this.divError.Style.Add("visibility", "visible");

                if (this.IsPostBack)
                {
                    Page.Response.Redirect(Page.Request.Url.AbsoluteUri + "?Guid=" + Guid.NewGuid().ToString());
                }
                return;
            }
            
            else
            {

                if (!this.IsPostBack)
                {
                    this.GetData(String.Format("Active = {0}", 1));
                    this.BindBD();
                    this.BindDPRoles();
                    this.BindDPCAT();
                    this.BindDPProvince();

                }
                if (returnvalue != null && returnvalue.Value != "")
                {
                    this.GetData(SearchCondition());
                    returnvalue.Value = "";
                }
            }
        }

        protected void GetData(string condition)
        {
            try
            {
                this.Pager1.Visible = true;
                DataTable dt = new DataTable();
                BEGDC.PreContract.BLL.IEmployee employee = (BEGDC.PreContract.BLL.IEmployee)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_Employee_Service];
                //dt = employee.GetEmployee_DataTable(condition);
                dt = employee.GetEmployeesByPCATOrRole_DataTable(condition);
                this.Pager1.BindtoGridView(this.gvEmployee, dt.DefaultView);

                if (dt.Rows.Count == 0)
                    this.Pager1.Visible = false;
            }
            catch (Exception ex)
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + ex.Message.Replace("'", "\\'") + "')</script>");
            }
        }

        protected string SearchCondition()
        {
            string condition = String.Empty;

            int active = Convert.ToInt32(this.chkActive.Checked);

            string cName = BaseFunction.SafeSQL(this.txtCName.Text.Trim());
            string eName = BaseFunction.SafeSQL(this.txtEName.Text.Trim());
            string adAccount = BaseFunction.SafeSQL(this.txtCIL.Text.Trim());
            string bd = this.BDDropDownList.SelectedValue;
            string phone = BaseFunction.SafeSQL(this.txtPhone.Text.Trim());
            string company = BaseFunction.SafeSQL(this.txtCompany.Text.Trim());
            string title = BaseFunction.SafeSQL(this.txtTitle.Text.Trim());
            string badge = BaseFunction.SafeSQL(this.txtBadge.Text.Trim());

            string catID = this.dpCAT.SelectedValue;
            string provinceID = this.dpProvinces.SelectedValue;
            string roleID = this.dpRoles.SelectedValue;

            condition = String.Format("Active = {0} ", active);

            if (!cName.Equals(String.Empty))
                condition += String.Format("AND CName LIKE N'%{0}%' ", cName);

            if (!eName.Equals(String.Empty))
                condition += String.Format("AND EName LIKE '%{0}%' ", eName);

            if (!adAccount.Equals(String.Empty))
                condition += String.Format("AND ADAccount LIKE '%{0}%' ", adAccount);

            if (!bd.Equals("Please select"))
                condition += String.Format("AND BD LIKE '%{0}%' ", bd);
            
            if(!phone.Equals(String.Empty))
                condition += String.Format("AND Phone LIKE '%{0}%' ", phone);

            if (!company.Equals(String.Empty))
                condition += String.Format("AND Company LIKE '%{0}%' ", company);

            if (!title.Equals(String.Empty))
                condition += String.Format("AND Title LIKE '%{0}%' ", title);

            if (!badge.Equals(String.Empty))
                condition += String.Format("AND Badge LIKE '%{0}%' ",badge);

            if (!catID.Equals(String.Empty))
                condition += String.Format("AND CATID = '{0}' ", catID);

            if (!provinceID.Equals(String.Empty))
                condition += String.Format("AND ProvinceID = '{0}' ", provinceID);

            if (!roleID.Equals(String.Empty))
                condition += String.Format("AND RoleID = '{0}' ", roleID);

            return condition;
        }

        protected void BindBD()
        {
            try
            {
                BEGDC.PreContract.BLL.IEmployee employee = (BEGDC.PreContract.BLL.IEmployee)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_Employee_Service];
                DataTable dt = employee.GetEmployeeBD();

                this.BDDropDownList.Items.Add("Please select");
                for (int i = 0; i < dt.Rows.Count; i++)
                    this.BDDropDownList.Items.Add(dt.Rows[i]["BD"].ToString());
            }
            catch (Exception ex)
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + ex.Message.Replace("'", "\\'") + "')</script>");
            }
        }

        /// <summary>
        /// Get roles list
        /// </summary>
        protected void BindDPRoles()
        {
            try
            {
                BEGDC.PreContract.BLL.IRole iRole = (BEGDC.PreContract.BLL.IRole)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_Role_Service];
                DataTable dt = iRole.GetRole_DataTable(string.Empty);

                this.dpRoles.DataSource = dt.DefaultView;
                this.dpRoles.DataValueField = "RoleID";
                this.dpRoles.DataTextField ="Description";
                this.dpRoles.DataBind();
                this.dpRoles.Items.Insert(0,new ListItem("Please select",""));
            }
            catch (Exception ex)
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + ex.Message.Replace("'", "\\'") + "')</script>");
            }
        }

        /// <summary>
        /// Get cat list
        /// </summary>
        protected void BindDPCAT()
        {
            try
            {
                BEGDC.PreContract.BLL.ICAT iCAT = (BEGDC.PreContract.BLL.ICAT)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_CAT_Service];
                DataTable dt = iCAT.GetCAT_DataTable("ACtive = 1");

                this.dpCAT.DataSource = dt.DefaultView;
                this.dpCAT.DataValueField = "CATID";
                this.dpCAT.DataTextField = "CATCode";
                this.dpCAT.DataBind();
                this.dpCAT.Items.Insert(0, new ListItem("Please select",""));
            }
            catch (Exception ex)
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + ex.Message.Replace("'", "\\'") + "')</script>");
            }
        }

        /// <summary>
        /// Get province list
        /// </summary>
        protected void BindDPProvince()
        {
            try
            {
                BEGDC.PreContract.BLL.IProvince iProvince = (BEGDC.PreContract.BLL.IProvince)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_Province_Service];
                DataTable dt = iProvince.GetProvince_DataTable("ACtive = 1");

                this.dpProvinces.DataSource = dt.DefaultView;
                this.dpProvinces.DataValueField = "ProvinceID";
                this.dpProvinces.DataTextField = "ProvinceCName";
                this.dpProvinces.DataBind();
                this.dpProvinces.Items.Insert(0, new ListItem("Please select",""));
            }
            catch (Exception ex)
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + ex.Message.Replace("'", "\\'") + "')</script>");
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                this.Pager1.GVCurrentPageIndex = 1;


                this.GetData(this.SearchCondition());

                
            }
            catch (Exception ex)
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + ex.Message.Replace("'", "\\'") + "')</script>");
            }
        }

        protected void gvEmployee_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex >= 0)
            {
                ImageButton imgedit = (ImageButton)e.Row.FindControl("imgedit");
                imgedit.Attributes.Add("onclick", "javascript:ShowPage('" + this.gvEmployee.DataKeys[e.Row.RowIndex].Value.ToString() + "');");

            }
        }

        protected bool[] CheckUserPermission()
        {
            BEGDC.PreContract.BLL.IUserRole iuser = (BEGDC.PreContract.BLL.IUserRole)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_UserRole_Service];

            DataTable dt = iuser.GetRoleListByEmployeeId(((BEGDC.PreContract.BLL.Authentication.PCIdentity)Page.User.Identity).EmployeeId);

            bool IsAdmin = false;
            bool IsRoleAdmin = false;
            string role = string.Empty;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                role = dt.Rows[i][0].ToString();
                if (role.Equals("1"))
                    IsAdmin = true;
                else if (role.Equals("4"))
                    IsRoleAdmin = true;
            }

            return new bool[] { IsAdmin, IsRoleAdmin };

        }
    }
}
